﻿using System;
using System.Linq;
using System.Web;
using BL.Abstract;
using DAL.Repositories;
using Model;

namespace BL.Class
{
    public class MasterFileBL : IMasterFileBL
    {
        private readonly UnitOfWork unitOfWork = new UnitOfWork();

        public int SaveNewMasterFile(string FileName, int inventoryId)
        {
            try
            {
                unitOfWork.MasterFileRepository.Insert(
                    new MASTERFILE
                    {
                        FileName = FileName,
                        FileUploadDate = DateTime.Now,
                        INVENTORYID = inventoryId,
                        ServerPath = FileName,
                        Status = "Zaladowany na serw",
                        TableName = "MBEW"
                    });
                unitOfWork.Save(HttpContext.Current.User.Identity.Name);
                return unitOfWork
                    .MasterFileRepository
                    .Get(i => i.FileName == FileName)
                    .First()
                    .MasterFileId;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public bool UpdateLoadedFile(bool processed, int masterFileId, int loadedRows, string msg)
        {
            try
            {
                var fileToUpdate =
                    unitOfWork
                    .MasterFileRepository
                    .Get(i => i.MasterFileId == masterFileId).First();
                if (fileToUpdate == null)
                {
                    return false;
                }
                fileToUpdate.Success = processed;                
                fileToUpdate.Processed = processed;
                fileToUpdate.RowNumber = loadedRows;
                fileToUpdate.Message = msg;
                unitOfWork.MasterFileRepository.Update(fileToUpdate);
                unitOfWork.Save(HttpContext.Current.User.Identity.Name);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
